package cn.azzhu.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * 实现离线计算：Dataset
 * @author azzhu
 * @create 2020-09-17 23:10:10
 */
public class BatchWordCount {

    public static void main(String[] args) throws Exception {
        final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //使用ExecutionEnvironment 创建DataSet
        final DataSet<String> lines = env.readTextFile("data/word");

        //切分压平
        final FlatMapOperator<String, Tuple2<String, Integer>> wordAndOne = lines.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String line, Collector<Tuple2<String, Integer>> out) throws Exception {
                final String[] words = line.split(" ");
                for (String word : words) {
                    out.collect(Tuple2.of(word, 1));
                }
            }
        });

        //离线计算实现的是分组聚合，调用的是groupBy
        final AggregateOperator<Tuple2<String, Integer>> sumed = wordAndOne.groupBy(0).sum(1);

        //将结果保存到hdfs
        sumed.writeAsText("data/result");

        env.execute("BatchWordCount");
    }
}
